<?php

namespace app\rider\services;


use app\admin\model\AdminModel;
use app\admin\model\CustomerModel;
use app\admin\model\ShopModel;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use think\facade\Cache;
use think\facade\Validate;
use Yansongda\Pay\Gateways\Alipay;

class RiderService
{
    protected static $key='zpf0321!@$!';

    /**
     * 登录操作生成token
     * @param $openid
     * @param $platform
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function login($openid, $platform)
    {
        $clientInfo = self::verifyLogin($openid,$platform);
        $returnAdminInfo = [
            "id" => $clientInfo->id,
            "openid" => $clientInfo->openid,
            'phone'=>$clientInfo->phone
        ];
        //缓存用户数据
        Cache::store("rider")->set("RIDERINFO_" . $clientInfo->id, $returnAdminInfo);
        $tokenInfo = self::createToken($clientInfo);
        return [
            'token' => $tokenInfo??"",
            'rider' => $returnAdminInfo??[],
        ];
    }

    /**
     * 登录验证
     * @param string $openid 平台openid
     * @param string $platform wx,dy,zfb
     * @return CustomerModel|array|mixed|\think\Model|null
     */
    protected static function verifyLogin($openid,$platform,$phone='')
    {
        $riderInfo=AdminModel::where([
            ['platform','=',$platform],
            ['openid','=',$openid]
        ])->find();
        if($riderInfo){
            $riderInfo->login_time = date('Y-m-d H:i:s');
            $riderInfo->ip = app('request')->ip();     //获取IP地址
            $riderInfo->login_count++;
            $riderInfo->openid=$openid;
            $riderInfo->save();
            return $riderInfo;
        }else{
            api_return(20001,'请绑定手机号码',['openid'=>$openid]);
        }
    }

    /**
     * 创建token
     * @param int $uid
     * @return string
     */
    public static function createToken($clientInfo)
    {
        $time = time(); //签发时间
        $token = array(
            "rider_id" => $clientInfo->id,
            "shop_id"=>$clientInfo->shop_id,
            "iss" => "yijiumei",//签发组织
            "aud" => "zpf",
            "iat" => $time,
            "nbf" => $time,
            "exp" => $time + env("LOGIN.LOGIN_EXPIRE_TIMEOUT") //过期时间
        );
        return JWT::encode($token, self::$key, "HS256");
    }

    /**
     * 解析token
     * @param string $jwt
     * @return bool
     */
    public static function parseToken(string $jwt)
    {
        try {
//            JWT::$leeway = 10;
            $jwtAuth = json_encode(JWT::decode($jwt, new Key(self::$key, "HS256")));
            $authInfo = json_decode($jwtAuth, true);
            $result = false;
            if (!empty($authInfo['rider_id'])) {
                $result = [
                    'rider_id'=>$authInfo['rider_id'],
                    'shop_id'=>$authInfo['shop_id']
                ];
            }
            return $result;
        } catch (\Firebase\JWT\ExpiredException $e) {
            api_return(20002, "登录超时，请重新登录".$e->getMessage());
            exit;
        } catch (SignatureInvalidException $e) {
            api_return(20002, $e->getMessage());
            exit;
        } catch (\Exception $e) {
            api_return(20002, $e->getMessage());
            exit;
        }
    }

    /**
     * 电话绑定
     * @param $p
     * @return void
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function bind($p){
        if(!empty($p['cipherText'])){
            $result=AlipayService::decrypt($p);
            $p['phone']=$result->mobile;
        }
        $rule=[
            'openid'=>'require',
            'phone'=>'require',
            'platform'=>'require|in:zfb'
        ];
        $validate=Validate::rule($rule);
        if(!$validate->check($p)){
            api_return(500,'something wrong,try again later.');
        }
        $riderInfo=AdminModel::where([
            ['platform','=',$p['platform']],
            ['phone','=',$p['phone']],
            ['role','=',3],
        ])->find();
        if($riderInfo){
            $riderInfo->openid=$p['openid'];
            $riderInfo->save();
        }else{
//            $p['account']=$p['nickname']='test';
//            $p['shop_id']=3;
//            $p['role']=3;
//            $riderInfo=AdminModel::editWithReturn($p);
            api_return(20001,'请联系管理员添加回收员手机号!');

        }
        $returnAdminInfo = [
            "id" => $riderInfo->id,
            "openid" => $riderInfo->openid,
            'phone'=>$riderInfo->phone
        ];
        //缓存用户数据
        Cache::store("rider")->set("RIDERINFO_" . $riderInfo->id, $returnAdminInfo);
        $tokenInfo = self::createToken($riderInfo);
        api_return(200,'',[
            'token' => $tokenInfo??"",
            'rider' => $returnAdminInfo??[],
        ]);

    }

    public static function info($p){
        $adminInfo=AdminModel::withoutField('last_login_time,head_pic,pwd,last_edit_pwd,avatar')->find($p['admin_id']);
        $shopInfo=ShopModel::field('name,address')->find($adminInfo->shop_id);
        api_return(200,'',[
            'adminInfo'=>$adminInfo,
            'shopInfo'=>$shopInfo
        ]);
    }
}
